import React, { useEffect, useState } from 'react';
import request from '@/utils/request';
import { Button, message, Card } from 'antd';

import styles from './index.less';
import NameModal from '@/components/NameModal';
import DirectoryTree from '@/components/Folder';
import AuthModal from './AuthModal';

const initData = [];

const FolderTree = (props) => {
  const { onNodeSelect } = props;
  const [data, setData] = useState(initData);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [selectedNode, setSelectedNode] = useState();
  const [authVisible, setAuthVisible] = useState(false);

  const loadTreeData = async () => {
    const response = await request(`/eofficeserver/api/folder?pfid=0`);
    setData([
      ...response,
      {
        title: '回收站',
        key: 'recyclebin',
        code: 'recyclebin',
        isLeaf: true,
      },
    ]);
    setLoading(loading);
  };
  const auths = { home: true, recyclebin: true };

  useEffect(() => {
    loadTreeData();
  }, []);

  const onSelect = (node) => {
    const { key } = node;
    setSelectedNode(node);
    if (onNodeSelect) {
      onNodeSelect(key);
    }
  };

  const onCreate = async (values) => {
    setVisible(false);
    setLoading(true);
    const response = await request('/eofficeserver/api/folder', {
      method: 'POST',
      data: { fname: values.name, pfid: selectedNode && selectedNode.key },
    });
    if (!response.success) {
      message.error(response.msg);
    } else {
      loadTreeData();
    }
    setLoading(false);
  };

  return (
    <Card
      title="位置"
      size="small"
      bordered={false}
      className={styles.sidebar}
      extra={<Button onClick={() => setVisible(true)}>添加</Button>}
      style={{ width: 300 }}
    >
      <DirectoryTree
        treeData={data}
        onNodeSelect={onSelect}
        titleRender={(nodeData) => {
          return (
            <div>
              {nodeData.title}
              {selectedNode?.key === nodeData.key && !auths[nodeData.code] && (
                <Button
                  type="link"
                  style={{ color: 'white' }}
                  onClick={(e) => {
                    e.stopPropagation();
                    setAuthVisible(true);
                  }}
                >
                  授权
                </Button>
              )}
            </div>
          );
        }}
      />
      <NameModal
        title="新建目录"
        initialValue={{ name: '新建目录' }}
        label="目录名称"
        visible={visible}
        onCreate={onCreate}
        onCancel={() => {
          setVisible(false);
        }}
      />
      {authVisible && (
        <AuthModal
          fid={selectedNode?.key}
          visible={authVisible}
          onCreate={onCreate}
          onCancel={() => {
            console.log('cancel');
            setAuthVisible(false);
          }}
        />
      )}
    </Card>
  );
};

export default FolderTree;
